package com.leo.nio.filechannel;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author du
 */
public class NioFileChannelCopy {

    public static void main(String[] args) throws IOException {

        // 原始文件1.txt
        FileInputStream fileInputStream = new FileInputStream("d:\\1.txt");
        FileChannel fileChannel1 = fileInputStream.getChannel();

        // 需要拷贝到的文件2.txt
        FileOutputStream fileOutputStream = new FileOutputStream("d:\\2.txt");
        FileChannel fileChannel2 = fileOutputStream.getChannel();

        // 创建buffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        /**
         * 1. 没有读取完, 则继续读, 直到-1
         * 2. 写入channel2时, 必须更改buffer为读模式
         * 3. 写完毕后, 需要重置buffer; 如果不复位, limit=position,永远返回0
         * 字母1字节, 汉字3字节(utf8), 换行符2字节
         */
        int i = 0;
        while ((i = fileChannel1.read(byteBuffer)) != -1) {

            byteBuffer.flip();                //读模式, position=0, limit=可用字节数
            fileChannel2.write(byteBuffer);   //position=limit=可用字节数
            fileChannel2.force(false);
            byteBuffer.clear();               //重置, position=0, limit=1024
        }

        fileChannel1.close();
        fileChannel2.close();
    }
}
